package com.wltt.product.ahuthr.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Author: wltt
 * @Date: 2019/12/02 14:49
 * @Version: 1.0
 * @Description: TODO
 */
public abstract class FileUtil {

    /**
     * 获取物理路径
     *
     * @param request request
     * @return
     */
    public static String getRealPath(HttpServletRequest request) {
        String path = request.getServletContext().getRealPath("/");
        if (!path.endsWith(File.separator)) {
            path = path + File.separator;
        }
        return path;
    }

    /**
     * 发生文件到前段，用于浏览器下载文件
     *
     * @param response 响应
     * @param sendFile 需要发送的文件
     */
    public static void SendFile(HttpServletResponse response, File sendFile) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.addHeader("Content-Length", "" + sendFile.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(sendFile.getName(), StandardCharsets.UTF_8));
        try (InputStream is = new FileInputStream(sendFile);
             BufferedInputStream bis = new BufferedInputStream(is);
             BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
            byte[] buff = new byte[2048];
            int len;
            while ((len = bis.read(buff)) != -1) {
                bos.write(buff, 0, len);
                bos.flush();
            }
            bos.flush();
        }
    }

    /**
     * 发生文件到前段，用于浏览器下载文件
     *
     * @param response 响应
     * @param fileContent 需要发送的文件内容
     */
    public static void SendFile(HttpServletResponse response, String fileName, long size, byte[] fileContent) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.addHeader("Content-Length", "" + size);
        response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        bos.write(fileContent);
        bos.flush();
    }


}
